package com.hmall.Service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.Mapper.ItemMapper;
import com.hmall.Service.SearchService;
import com.hmall.common.dto.PageDTO;
import com.hmall.pojo.Item;
import com.hmall.pojo.ItemDoc;
import com.hmall.pojo.RequestParams;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceimpl extends ServiceImpl<ItemMapper,Item> implements SearchService {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全
     *
     * @param key
     * @return
     */
    public List<String> Itemsuggestion(String key) {

        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hmmall");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

            return list;


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageDTO PageItem(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest("hmmall");

            buildBasicQuery(params, request);

            int page = params.getPage();
            int size = params.getSize();

            request.source().from((page - 1) * size).size(size);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    //结果解析
    private PageDTO handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();

        long total = searchHits.getTotalHits().value;

        System.out.println("查询到" + total + "条数据");

        SearchHit[] hits = searchHits.getHits();

        ArrayList<ItemDoc> hotels = new ArrayList<>();

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    itemDoc.setName(name);
                }
            }


            hotels.add(itemDoc);
        }
        return new PageDTO(total, hotels);
    }

    //搜索条件构建
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        String key = params.getKey();

        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //分类
        if (params.getCategory() != null && !"".equals(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //品牌
        if (params.getBrand() != null && !"".equals(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
        request.source().query(boolQuery);
    }

    /**
     * 搜索栏聚合
     *
     * @param params
     * @return
     */
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hmmall");

            buildBasicQuery(params, request);

            request.source().size(0);
            //聚合
            buildAggregation(request);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Map<String,List<String>> result = new HashMap<>();

            Aggregations aggregations = response.getAggregations();

            List<String> categoryAgg = getAggByName(aggregations, "categoryAgg");
            result.put("category",categoryAgg);

            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand",brandAgg);

            return  result;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
        );
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName){
        Terms brandTerms = aggregations.get(aggName);

        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();

        List<String> brandList = new ArrayList<>();

        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }


    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hmmall", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void insertById(Long id) {
        try {
            Item item = getById(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hmmall").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
